#include "cvnetworkmanager.h"

CVNetworkManager *CVNetworkManager::instance = NULL;

CVNetworkManager::CVNetworkManager()
{

}

CVNetworkManager::~CVNetworkManager()
{

}

CVNetworkManager *CVNetworkManager::get()
{
    if (!instance)
    {
        instance = new CVNetworkManager();
    }
    return instance;
}

void CVNetworkManager::clear()
{
    instance = NULL;
}

void CVNetworkManager::validateNetwork(const QString &url)
{
    CVHttp *http = new CVHttp(CVUtil::getBaseUrl("mobile.get_network_info", url));
    connect(http, SIGNAL(finished(QScriptValue,QString)), this, SLOT(handleData(QScriptValue,QString)));
    connect(http, SIGNAL(handleError(QNetworkReply::NetworkError)), this, SLOT(handError(QNetworkReply::NetworkError)));
}

void CVNetworkManager::handleData(QScriptValue result, const QString &message)
{
    bool bResult = false;
    if (!result.isNull() && !result.isError())
    {
        QScriptValue isEcoRoot = result.property("is_eco_root_network");
        if (!isEcoRoot.toBool()) {
            bResult = true;
        }
    }
    emit validated(bResult);
}

void CVNetworkManager::handError(QNetworkReply::NetworkError error)
{
    emit validated(false);
}
